package com.example.lj.uav.view;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.lj.uav.MyApplication;
import com.example.lj.uav.R;
import com.example.lj.uav.adapter.FileAdapter;
import com.example.lj.uav.bean.RouteLine;
import com.example.lj.uav.bean.RoutePoint;
import com.example.lj.uav.dao.MyDBDao;
import com.example.lj.uav.utils.KmlUtils;
import com.example.lj.uav.view.adapter.ViewPagerAdapter;
import com.example.lj.uav.view.base.BaseActivity;
import com.example.lj.uav.view.fragment.FragmentRouteMenuCollection;
import com.example.lj.uav.view.fragment.FragmentRouteMenuLine;
import com.example.lj.uav.widget.CommomDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class RouteMenuActivity extends BaseActivity implements View.OnClickListener,Handler.Callback {
    private ViewPager viewPager;
    private FragmentRouteMenuLine fragmentRoute;
    private FragmentRouteMenuCollection fragmentCollection;
    private View mBar;

    private RelativeLayout mRlSelectBar;
    private LinearLayout mLlBottomBar;
    private RelativeLayout mRlSearchBar;
    private RelativeLayout mRlSearchNull;
    private ImageView mIvFilter;
    private List<Fragment> viewList = new ArrayList<>();
    private ViewPagerAdapter viewPagerAdapter;

    public TextView mTvSelected;
    private EditText mEtSearch;
    private ImageView mIvSearch;
    private TextView mTvSelect;
    private ImageView mIvCopy;



    private int currentPage;
    private int length;
    private PopupWindow popupWindow;
    private MyDBDao dao;

    private File[] fileList;
    private FileAdapter fileAdapter;
    private int selectedFilePosition;
    private AlertDialog fileSelectBrowser;
    private AlertDialog storageSelect;
    private RecyclerView rev_file_list;
    private ImageView ivBack;
    private TextView tv_path;
//    private String currentFilePath;
    private String rootPath;
    private Handler handler;

    public boolean isImport;
    private TextView tv_no_data;
    private File currentFile;
    private RelativeLayout mRlExport;
    private TextView mTvExport;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_line_menu);
        permission();
        initView();
        dao = MyApplication.dao;
        handler = new Handler(this);
    }

    private void permission() {
        String[] REQUIRED_PERMISSION_LIST = new String[]{
                Manifest.permission.VIBRATE,
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.WAKE_LOCK,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
        };
        List<String> missingPermission = new ArrayList<>();
        final int REQUEST_PERMISSION_CODE = 12345;

        // Check for permissions
        for (String eachPermission : REQUIRED_PERMISSION_LIST) {
            if (ContextCompat.checkSelfPermission(this, eachPermission) != PackageManager.PERMISSION_GRANTED) {
                missingPermission.add(eachPermission);
            }
        }
        // Request for missing permissions
        if (missingPermission.isEmpty()) {
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            showToast("Need to grant the permissions!");
            ActivityCompat.requestPermissions(this,
                    missingPermission.toArray(new String[missingPermission.size()]),
                    REQUEST_PERMISSION_CODE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        length = dip2px(this,110);
    }

    private void initView() {
        mBar = findViewById(R.id.v_route_bar);
        mRlSelectBar = findViewById(R.id.rl_route_menu_select_title);
        mLlBottomBar = findViewById(R.id.ll_route_menu_bottom_bar);
        mRlSearchBar = findViewById(R.id.rl_route_menu_search_bar);
        mRlSearchNull = findViewById(R.id.rl_route_menu_search_no_result);
        mIvFilter = findViewById(R.id.iv_route_menu_filter);
        mTvSelected = findViewById(R.id.tv_route_menu_select_qty);
        mEtSearch = findViewById(R.id.et_route_menu_search);
        mIvFilter.setOnClickListener(this);
        mTvSelect = findViewById(R.id.tv_route_title_select_btn);
        mTvSelect.setOnClickListener(this);
        findViewById(R.id.tv_route_title_complete_btn).setOnClickListener(this);

        findViewById(R.id.tv_route_storage).setOnClickListener(this);
        findViewById(R.id.tv_collection).setOnClickListener(this);
        findViewById(R.id.btn_route_menu_search_cancel).setOnClickListener(this);
        mIvSearch = findViewById(R.id.iv_route_menu_search);
        mIvSearch.setOnClickListener(this);
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.iv_collect).setOnClickListener(this);
        mIvCopy = findViewById(R.id.iv_copy);
        mIvCopy.setOnClickListener(this);
        findViewById(R.id.iv_delete).setOnClickListener(this);
        findViewById(R.id.iv_export).setOnClickListener(this);
        fragmentRoute = new FragmentRouteMenuLine();
        fragmentCollection = new FragmentRouteMenuCollection();
        viewPager = findViewById(R.id.vp_menu);
        viewList.add(fragmentRoute);
        viewList.add(fragmentCollection);

        FragmentManager fm = getSupportFragmentManager();
        viewPagerAdapter = new ViewPagerAdapter(fm,viewList);

        viewPager.setAdapter(viewPagerAdapter);
        viewPager.setCurrentItem(0);
        currentPage = 0;

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Log.e("info","onPageScrolled调用");
            }

            @Override
            public void onPageSelected(int position) {
                Log.e("info","onPageSelected调用");
                switch (position){
                    case 0:
                        if (currentPage==1){
                            barToLeft();
                            currentPage = 0;
                        }
                        break;
                    case 1:
                        if (currentPage==0){
                            barToRight();
                            currentPage = 1;
                        }
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }

        });

        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String content = editable.toString();
                if (content.length()<=0){
                    return;
                }
                if (currentPage==0){
                    fragmentRoute.onSearchButtonPressed(content);
                }else{
                    fragmentCollection.onSearchButtonPressed(content);
                }
            }
        });
    }

    public void showStorageSelectDialog(boolean isImport) {
        this.isImport = isImport;
        View view = getLayoutInflater().inflate(R.layout.dialog_storage_select,null);
        LinearLayout llOut = view.findViewById(R.id.ll_out_storage);
        LinearLayout llInner = view.findViewById(R.id.ll_inner_storage);
        llInner.setVisibility(View.GONE);
        TextView tv_out_name = view.findViewById(R.id.tv_out_storage_name);
        TextView tv_out_size = view.findViewById(R.id.tv_out_storage_size);
        TextView tv_inner_name = view.findViewById(R.id.tv_inner_storage_name);
        TextView tv_inner_size = view.findViewById(R.id.tv_inner_storage_size);
        llOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showFileBrowser();
            }
        });

        storageSelect = new AlertDialog.Builder(this).setView(view).create();
        storageSelect.show();
    }


    private void showFileBrowser() {
//        mainPath = Environment.getExternalStorageDirectory().getAbsolutePath();
//        Toast.makeText(getActivity(), mainPath,Toast.LENGTH_SHORT).show();
        View view = this.getLayoutInflater().inflate(R.layout.dialog_file_browser,null);
        ivBack = view.findViewById(R.id.iv_file_select_back);
        tv_path = view.findViewById(R.id.tv_file_select_path);
        rev_file_list = view.findViewById(R.id.rev_file_list);
        tv_no_data = view.findViewById(R.id.tv_file_no_data);
        mRlExport = view.findViewById(R.id.rl_export);
        mTvExport = view.findViewById(R.id.tv_export);

        if (isImport){
            mRlExport.setVisibility(View.GONE);
        }else{
            mRlExport.setVisibility(View.VISIBLE);
        }
        mTvExport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentPage==0){
                    fragmentRoute.exportButtonPressed(currentFile.getPath());
                }else{
                    fragmentCollection.exportButtonPressed(currentFile.getPath());
                }

            }
        });

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (rootPath.equals(currentFile.getPath())){
                    return;
                }
                String path = currentFile.getParent();
                getFileList(path);
            }
        });
        fileSelectBrowser = new AlertDialog.Builder(this).setView(view).create();
        fileSelectBrowser.show();

        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
        rootPath = file.getPath();
        LinearLayoutManager llm = new LinearLayoutManager(this);
        rev_file_list.setLayoutManager(llm);
        getFileList(file.getPath());
//        currentFilePath = rootPath;
//        tv_path.setText(rootPath);
//        fileList = file.listFiles();
//        fileAdapter = new FileAdapter(fileList,this,handler);
//        rev_file_list.setAdapter(fileAdapter);

    }


    private void getFileList(String path) {
        tv_path.setText(path);
        currentFile = new File(path);
        File[] resultList = currentFile.listFiles();
        List<File> list = new ArrayList<>();
        for (int i=0;i<resultList.length;i++){
            File file1 = resultList[i];
            if (file1.isDirectory()){
                list.add(file1);
            }
            if (isImport&&file1.getName().endsWith(".kml")){
                list.add(file1);
            }
        }
        fileList = new File[list.size()];
        for (int i=0;i<list.size();i++){
            fileList[i] = list.get(i);
        }
        if(fileList.length<=0){
            rev_file_list.setVisibility(View.GONE);
            tv_no_data.setVisibility(View.VISIBLE);
            return;
        }
        rev_file_list.setVisibility(View.VISIBLE);
        tv_no_data.setVisibility(View.GONE);
        fileAdapter = new FileAdapter(fileList,this,handler);
        rev_file_list.setAdapter(fileAdapter);
    }


    private void barToRight(){
        ObjectAnimator animator = ObjectAnimator.ofFloat(mBar,"translationX",0, length);
        animator.setDuration(200);
        animator.start();
    }

    private void barToLeft(){
        ObjectAnimator animator = ObjectAnimator.ofFloat(mBar,"translationX", length,0);
        animator.setDuration(200);
        animator.start();
    }


    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    @Override
    public void onClick(View view) {
        int qty;
        if (currentPage == 0){
            qty= fragmentRoute.selectedQty;
        }else{
            qty= fragmentCollection.selectedQty;
        }

        switch (view.getId()){
            case R.id.tv_route_storage:
                viewPager.setCurrentItem(0);
                break;
            case R.id.tv_collection:
                viewPager.setCurrentItem(1);
                break;
            case R.id.tv_route_title_select_btn:
                mRlSelectBar.setVisibility(View.VISIBLE);
                mLlBottomBar.setVisibility(View.VISIBLE);
                if (currentPage==0){
                    fragmentRoute.selectButtonPressed();
                    mIvCopy.setVisibility(View.VISIBLE);
                }else{
                    mIvCopy.setVisibility(View.GONE);
                    fragmentCollection.selectButtonPressed();
                }
                break;
            case R.id.tv_route_title_complete_btn:
                mRlSelectBar.setVisibility(View.GONE);
                mLlBottomBar.setVisibility(View.GONE);
                if (currentPage==0){
                    fragmentRoute.completeButtonPressed();
                }else{
                    fragmentCollection.completeButtonPressed();
                }
                break;
            case R.id.btn_route_menu_search_cancel:
                mRlSearchBar.setVisibility(View.GONE);
                mRlSearchNull.setVisibility(View.GONE);
                if (currentPage==0){
                    fragmentRoute.onSearchCanceled();
                }else{
                    fragmentCollection.onSearchCanceled();
                }
                break;
            case R.id.iv_route_menu_search:
                mRlSearchBar.setVisibility(View.VISIBLE);
                mRlSearchNull.setVisibility(View.VISIBLE);
                if (currentPage == 0) {
                    fragmentRoute.onSearchMenuPressed();
                }else{
                    fragmentCollection.onSearchMenuPressed();
                }
                break;
            case R.id.iv_route_menu_filter:
                showPopupWindow();
                break;
            case R.id.iv_back:
                RouteMenuActivity.this.finish();
                break;
            case R.id.iv_collect:
                if (qty==0){
                    showToast("没有选中的任务");
                    return;
                }
                if (currentPage == 0) {
                    fragmentRoute.collectButtonPressed();
                }else{
                    fragmentCollection.collectButtonPressed();
                }
                break;
            case R.id.iv_delete:
                if (qty==0){
                    showToast("没有选中的任务");
                    return;
                }
                if (currentPage == 0) {
                    fragmentRoute.deleteButtonPressed();
                }else{
                    fragmentCollection.deleteButtonPressed();
                }
                break;
            case R.id.iv_copy:
                if (qty==0){
                    showToast("没有选中的任务");
                    return;
                }
                new CommomDialog(this, R.style.commondialog, "是否复制当前选中的任务？", new CommomDialog.OnCloseListener() {
                    @Override
                    public void onClick(CommomDialog dialog, boolean confirm) {
                        if (confirm){
                            fragmentRoute.copyButtonPressed();
                        }
                        dialog.dismiss();
                    }
                }).setTitle("提示").show();
                break;
            case R.id.iv_export:
                if (qty==0){
                    showToast("没有选中的任务");
                    return;
                }
                showStorageSelectDialog(false);
                break;
        }
    }

    private void showPopupWindow() {
        View convertView = LayoutInflater.from(this).inflate(R.layout.popup_route_filter,null);
        RadioGroup radioGroup1 = convertView.findViewById(R.id.rg_route_filter_list);
        radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.rb_route_filter_time:
                        if (currentPage==0){
                            fragmentRoute.listByTime();
                        }else{
                            fragmentCollection.listByTime();
                        }
                        break;
                    case R.id.rb_route_filter_name:
                        if (currentPage==0){
                            fragmentRoute.listByName();
                        }else{
                            fragmentCollection.listByName();
                        }
                        break;
                }
            }
        });

        RadioGroup radioGroup2 = convertView.findViewById(R.id.rg_route_filter_type);
        final RadioButton rbAll = convertView.findViewById(R.id.rb_route_filter_all_type);
        final RadioButton rbArea = convertView.findViewById(R.id.rb_route_filter_area);
        final CheckBox cb = convertView.findViewById(R.id.cb_route_filter_point);
        radioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.rb_route_filter_all_type:
                        if (rbAll.isChecked()){
                            cb.setChecked(false);
                            if (currentPage == 0){
                                fragmentRoute.showAllTypeRoute();
                            }else{
                                fragmentCollection.showAllTypeRoute();
                            }
                            break;
                        }
                    case R.id.rb_route_filter_area:
                        if (rbArea.isChecked()){
                            if (currentPage == 0){
                                fragmentRoute.showAreaTypeRoute();
                            }else{
                                fragmentCollection.showAreaTypeRoute();
                            }
                            cb.setChecked(false);
                        }
                        break;
                }
            }
        });

        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b){
                    if (rbAll.isChecked()){
                        rbAll.setChecked(false);
                    }
                    if (rbArea.isChecked()){
                        rbArea.setChecked(false);
                    }
                    if (currentPage == 0){
                        fragmentRoute.showLineTypeRoute();
                    }else{
                        fragmentCollection.showLineTypeRoute();
                    }
                }
            }
        });

        if (popupWindow==null){
            popupWindow = new PopupWindow(convertView,RadioGroup.LayoutParams.WRAP_CONTENT,RadioGroup.LayoutParams.WRAP_CONTENT,true);
        }
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return false;
            }
        });

        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.popup_grey_bg));
        popupWindow.showAsDropDown(mIvFilter,-500,50);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (fragmentRoute.mRlMenu.getVisibility()==View.VISIBLE){
//            fragmentRoute.mRlMenu.setVisibility(View.GONE);
//            return false;
//        }
        if (popupWindow!=null&&popupWindow.isShowing()){
            popupWindow.dismiss();
            return false;
        }
        if (mRlSelectBar.getVisibility()==View.VISIBLE){
            mRlSelectBar.setVisibility(View.GONE);
            mLlBottomBar.setVisibility(View.GONE);
            return false;
        }
        if (mRlSearchBar.getVisibility()==View.VISIBLE){
            mRlSearchBar.setVisibility(View.GONE);
            mRlSearchNull.setVisibility(View.GONE);
            if (currentPage==0){
                fragmentRoute.onSearchCanceled();
            }else{
                fragmentCollection.onSearchCanceled();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void searchNoData() {
        mRlSearchNull.setVisibility(View.VISIBLE);
    }

    public void searHasData() {
        mRlSearchNull.setVisibility(View.GONE);
    }

    public void updateButtonStatus(int size) {
        if (size>0){
            mIvSearch.setEnabled(true);
            mTvSelect.setEnabled(true);
        }else{
            mIvSearch.setEnabled(false);
            mTvSelect.setEnabled(false);
        }
    }

    public List<String> getFileNames() {
        return fragmentRoute.getFileNames();
    }

    public void updateMenuList() {
        fragmentRoute.getLineData();
    }

    public void updateCollectList(){
        fragmentCollection.getLineData();
    }

    @Override
    public boolean handleMessage(Message message) {
        selectedFilePosition = message.arg1;
        File file = fileList[selectedFilePosition];
        switch (message.what){
            case FileAdapter.FILE_FOLDER_SELECTED:
                getFileList(file.getPath());
                break;
            case FileAdapter.FILE_SELECTED:
                //解析kml文件并保存到数据库
                try {
                    KmlUtils.parseKml(file.getPath());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                RouteLine line = KmlUtils.readKmlForLine();
                List<RoutePoint> points = KmlUtils.readKmlForPoint();
                dao.addRoute(line);
                for (int i=0;i<points.size();i++){
                    dao.addPoint(i,points.get(i),line.getFileName());
                    dao.addPointActions(line.getFileName(),points.get(i));
//                dao.addPointActions(fileName,points.get(i));
                }
                fragmentRoute.getLineData();
                fileSelectBrowser.dismiss();
                storageSelect.dismiss();
                showToast("导入成功！");
                break;
        }
        return false;
    }

    public void upDateSelectButton(boolean enable) {
        mTvSelect.setEnabled(enable);
        mIvFilter.setEnabled(enable);
        mIvSearch.setEnabled(enable);
        if (enable){
            mTvSelect.setTextColor(getResources().getColor(R.color.dodgerblue));
        }else{
            mTvSelect.setTextColor(getResources().getColor(R.color.gray));
        }
    }
}
